package com.ztools.pc.service.impl.information;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ztools.common.model.pc.information.Grade;
import com.ztools.common.model.pc.information.Teacher;
import com.ztools.common.util.common.PageUtil;
import com.ztools.pc.mapper.information.GradeMapper;
import com.ztools.pc.service.information.GradeService;
import com.ztools.pc.service.information.TeacherService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:一口香菜
 * @Date: 2023/3/12  13:06
 * @Version 1.0
 */
@Service
public class GradeServiceImpl extends ServiceImpl<GradeMapper, Grade> implements GradeService {

    @Resource
    private TeacherService teacherService;

    @Override
    public Page<Grade> findList(PageUtil<Grade> pageUtil) {
        List<OrderItem> orders = new ArrayList<>();
        QueryWrapper<Grade> queryWrapper = getQueryWrapper(pageUtil.getParams());
        Page<Grade> pages = new Page<>(pageUtil.getPage(), pageUtil.getSize());
        // 排序数据  StrUtil.toUnderlineCase huTools将驼峰装换为下划线格式
        orders.add(new OrderItem(StrUtil.toUnderlineCase(pageUtil.getSortName()), "asc".equals(pageUtil.getSortOrder())));
        pages.setOrders(orders);
        Page<Grade> page = page(pages, queryWrapper);
        dictionary(page.getRecords());
        return pages;
    }

    @Override
    public List<Grade> findByObject(Grade grade) {
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>(grade);
        return list(queryWrapper);
    }

    /**
     * 获取拼装条件
     * PS：有模糊查询的需求时才使用这种方法来查询，没有则直接new QueryWrapper时放入对象即可
     *
     * @param grade grade
     * @return
     */
    public QueryWrapper<Grade> getQueryWrapper(Grade grade) {
        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(grade.getName())) {
            gradeQueryWrapper.like("name", grade.getName());
        }
        return gradeQueryWrapper;
    }

    @Override
    public boolean update(Grade grade) {
        boolean b = false;
        Grade byId = getById(grade);
        updateById(grade);
        return true;
    }

    /**
     * 字典翻译
     *
     * @param gradeList 对象集合
     */
    public void dictionary(List<Grade> gradeList) {
        for (Grade grade : gradeList) {
            dictionary(grade);
        }
    }

    public void dictionary(Grade grade) {
        if (grade != null) {
            // 班主任翻译
            if (grade.getDirector() != null) {
                Teacher teacher = teacherService.getById(grade.getDirector());
                grade.setDirectorName(teacher.getName());
            }
        }
    }


}
